/**
 * @file XListViewHeader.java
 * @create Apr 18, 2012 5:22:27 PM
 * @author Maxwin
 * @description XListView's header
 */
package www.com.library.view;

import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Color;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.util.Date;

import www.com.common.library.R;
import www.com.library.util.StringFormatter;

public class RecyclerViewHeader extends LinearLayout {

    private RelativeLayout mContainer;
    private XRecyclerHeaderProgress mArrowImageView;
    private ProgressBar mProgressBar;
    private TextView mHintTextView;
    private TextView mHeaderTimeView;
    private View mLastTime;
    private int mState = STATE_NORMAL;

    private Animation mRotateUpAnim;
    private Animation mRotateDownAnim;

    public int mMeasuredHeight;

    private final int ROTATE_ANIM_DURATION = 180;

    public static final int STATE_NORMAL = 0;
    public static final int STATE_RELEASE_TO_REFRESH = 1;
    public static final int STATE_REFRESHING = 2;
    public static final int STATE_DONE = 3;

    private Date mRefreshDate;

    public RecyclerViewHeader(Context context) {
        super(context);
        initView(context);
    }

    public RecyclerViewHeader(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }

    private void initView(Context context) {
        // 初始情况，设置下拉刷新view高度为0
        mContainer = (RelativeLayout) LayoutInflater.from(getContext()).inflate(
                R.layout.listview_header, null);
        LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        lp.setMargins(0, 0, 0, 0);
        this.setLayoutParams(lp);
        this.setPadding(0, 0, 0, 0);

        addView(mContainer, new LayoutParams(LayoutParams.MATCH_PARENT, 0));
        setGravity(Gravity.BOTTOM);

        mArrowImageView = (XRecyclerHeaderProgress) findViewById(R.id.xlistview_header_arrow);
        mArrowImageView.setBorderColor(0xFFB9B9B9);
        mHintTextView = (TextView) findViewById(R.id.xlistview_header_hint_textview);
        mProgressBar = (ProgressBar) findViewById(R.id.xlistview_header_progressbar);
        mHeaderTimeView = (TextView) findViewById(R.id.xlistview_header_time);
        mLastTime = findViewById(R.id.xlistview_header_last_time_ll);

        mRotateUpAnim = new RotateAnimation(0.0f, -180.0f,
                Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
                0.5f);
        mRotateUpAnim.setDuration(ROTATE_ANIM_DURATION);
        mRotateUpAnim.setFillAfter(true);
        mRotateDownAnim = new RotateAnimation(-180.0f, 0.0f,
                Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
                0.5f);
        mRotateDownAnim.setDuration(ROTATE_ANIM_DURATION);
        mRotateDownAnim.setFillAfter(true);

        measure(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        mMeasuredHeight = getMeasuredHeight();

        //设置整体的背景色
        setBackgroundColor(Color.parseColor("#F5F5F5"));
    }

    public void setState(int state) {
        if (state == mState) return;

        if (state == STATE_REFRESHING) {    // 显示进度
            //mArrowImageView.clearAnimation();
            mArrowImageView.setVisibility(View.INVISIBLE);
            mProgressBar.setVisibility(View.VISIBLE);
        } else if (state == STATE_DONE) {
            mArrowImageView.setVisibility(View.INVISIBLE);
            mProgressBar.setVisibility(View.INVISIBLE);
        } else {    // 显示箭头图片
            mArrowImageView.setVisibility(View.VISIBLE);
            mProgressBar.setVisibility(View.INVISIBLE);
        }

        switch (state) {
            case STATE_NORMAL:
                /*if (mState == STATE_RELEASE_TO_REFRESH) {
                    mArrowImageView.startAnimation(mRotateDownAnim);
                }
                if (mState == STATE_REFRESHING) {
                    mArrowImageView.clearAnimation();
                }*/
                mHintTextView.setText(R.string.listview_header_hint_normal);
                mLastTime.setVisibility(VISIBLE);
                break;
            case STATE_RELEASE_TO_REFRESH:
                if (mState != STATE_RELEASE_TO_REFRESH) {
                    /*mArrowImageView.clearAnimation();
                    mArrowImageView.startAnimation(mRotateUpAnim);*/
                    mHintTextView.setText(R.string.listview_header_hint_ready);
                    mLastTime.setVisibility(GONE);
                }
                break;
            case STATE_REFRESHING:
                mHintTextView.setText(R.string.listview_header_hint_loading);
                mLastTime.setVisibility(GONE);
                break;
            case STATE_DONE:
                mHintTextView.setText(R.string.listview_header_hint_done);
                mLastTime.setVisibility(GONE);
                break;
            default:
        }

        mState = state;
    }

    public int getState() {
        return mState;
    }

    public void refreshComplete() {
        mHeaderTimeView.setText(friendlyTime2(new Date()));
        setState(STATE_DONE);
        new Handler().postDelayed(new Runnable() {
            public void run() {
                reset();
            }
        }, 200);
    }

    public void setVisibleHeight(int height) {
        if (height < 0) height = 0;
        LayoutParams lp = (LayoutParams) mContainer.getLayoutParams();
        lp.height = height;
        mContainer.setLayoutParams(lp);
    }

    public int getVisibleHeight() {
        LayoutParams lp = (LayoutParams) mContainer.getLayoutParams();
        return lp.height;
    }

    public void onMove(float delta) {
        if (getVisibleHeight() > 0 || delta > 0) {
            setVisibleHeight((int) delta + getVisibleHeight());
            if (mState <= STATE_RELEASE_TO_REFRESH) { // 未处于刷新状态，更新箭头
                int visibleHeight = getVisibleHeight();
                mArrowImageView.setMax(mMeasuredHeight);
                mArrowImageView.setProgress(visibleHeight);
                if (visibleHeight > mMeasuredHeight) {
                    setState(STATE_RELEASE_TO_REFRESH);
                } else {
                    setState(STATE_NORMAL);
                }
            }
        }
    }

    public boolean releaseAction() {
        boolean isOnRefresh = false;
        int height = getVisibleHeight();
        if (height == 0) // not visible.
            isOnRefresh = false;

        if (getVisibleHeight() > mMeasuredHeight && mState < STATE_REFRESHING) {
            setState(STATE_REFRESHING);
            isOnRefresh = true;
        }
        // refreshing and header isn't shown fully. do nothing.
        if (mState == STATE_REFRESHING && height <= mMeasuredHeight) {
            //return;
        }
        int destHeight = 0; // default: scroll back to dismiss header.
        // is refreshing, just scroll back to show all the header.
        if (mState == STATE_REFRESHING) {
            destHeight = mMeasuredHeight;
        }
        smoothScrollTo(destHeight);

        return isOnRefresh;
    }

    public void reset() {
        smoothScrollTo(0);
        new Handler().postDelayed(new Runnable() {
            public void run() {
                setState(STATE_NORMAL);
            }
        }, 500);
    }

    private void smoothScrollTo(int destHeight) {
        ValueAnimator animator = ValueAnimator.ofInt(getVisibleHeight(), destHeight);
        animator.setDuration(300).start();
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                setVisibleHeight((int) animation.getAnimatedValue());
            }
        });
        animator.start();
    }

    public String friendlyTime2(Date time) {
        if (time == null) {
            time = new Date();
        }
        mRefreshDate = time;
        return StringFormatter.instance().toTime(mRefreshDate);
    }

    /**
     * 更改刷新时间的时区
     */
    public void changeRefreshDateTimeZone() {
        if (mRefreshDate == null) {
            mRefreshDate = new Date();
        }
        mHeaderTimeView.setText(StringFormatter.instance().toTime(mRefreshDate));
    }

    public String friendlyTime(Date time) {
        //获取time距离当前的秒数
        int ct = (int) ((System.currentTimeMillis() - time.getTime()) / 1000);

        if (ct == 0) {
            return getContext().getResources().getString(R.string.listview_header_time_0);
        }

        if (ct > 0 && ct < 60) {
            return ct + getContext().getResources().getString(R.string.listview_header_time_1);
        }

        if (ct >= 60 && ct < 3600) {
            return Math.max(ct / 60, 1) + getContext().getResources().getString(R.string.listview_header_time_2);
        }
        if (ct >= 3600 && ct < 86400)
            return ct / 3600 + getContext().getResources().getString(R.string.listview_header_time_3);
        if (ct >= 86400 && ct < 2592000) { //86400 * 30
            int day = ct / 86400;
            return day + getContext().getResources().getString(R.string.listview_header_time_4);
        }
        if (ct >= 2592000 && ct < 31104000) { //86400 * 30
            return ct / 2592000 + getContext().getResources().getString(R.string.listview_header_time_5);
        }
        return ct / 31104000 + getContext().getResources().getString(R.string.listview_header_time_6);
    }

}
